/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.view;

import entity.JobDetails;
import entity.Users;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
import session.JobActionFacade;
import session.JobDetailsFacade;
import session.JobItemsFacade;
import session.JobsFacade;

/**
 *
 * @author owtee
 */
public class ApplicationAddJob extends HttpServlet {

    @EJB
    private JobItemsFacade jobItemsFacade;
    @EJB
    private JobActionFacade jobActionFacade;
    @EJB
    private JobsFacade jobsFacade;
    @EJB
    private JobDetailsFacade jobDetailsFacade;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/xml;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            try {
                String jobId = request.getParameter("jobId");
                String jobActionId = request.getParameter("jobActionId");
                String jobItemId = request.getParameter("jobItemId");
                String jobDesc = request.getParameter("jobDesc");

                // Get session
                HttpSession session = request.getSession();
                Users member = (Users) session.getAttribute("member");

                JobDetails jobDetail = new JobDetails();
                jobDetail.setJobId(jobsFacade.find(jobId));
                jobDetail.setActionId(jobActionFacade.find(Integer.parseInt(jobActionId)));
                jobDetail.setItemId(jobItemsFacade.find(Integer.parseInt(jobItemId)));
                jobDetail.setDescription(jobDesc);
                jobDetail.setActiveFlag(true);
                jobDetail.setCreateUser(member.getUserId());
                jobDetail.setCreateDate(new Date());
                jobDetail.setModifyUser(member.getUserId());
                jobDetail.setModifyDate(new Date());
                jobDetailsFacade.create(jobDetail);

                // Find all job
                List<JobDetails> jobDetailLst = jobDetailsFacade.findByJobId(jobId);

                // Create xml
                DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
                //creating a new instance of a DOM to build a DOM tree.
                Document doc = docBuilder.newDocument();
                //new XmlServlet().createXmlTree(doc);

                Element msg = doc.createElement("Messenger");
                doc.appendChild(msg);

                // Create element summary contract data            
                Element tagJobDetailSize = doc.createElement("JobDetailSize");
                tagJobDetailSize.setAttribute("NumRecData", Integer.toString(jobDetailLst.size()));
                msg.appendChild(tagJobDetailSize);
                // Create element contract
                for (JobDetails jobDetailI : jobDetailLst) {
                    Element tagJobDetail = doc.createElement("JobDetail");
                    msg.appendChild(tagJobDetail);
                    Element tagJobDetailId = doc.createElement("Id");
                    tagJobDetail.appendChild(tagJobDetailId);
                    Text txtJobDetailId = doc.createTextNode(jobDetailI.getDetailId().toString());
                    tagJobDetailId.appendChild(txtJobDetailId);
                    Element tagJobId = doc.createElement("JobId");
                    tagJobDetail.appendChild(tagJobId);
                    Text txtJobId = doc.createTextNode(jobDetailI.getJobId().getJobId());
                    tagJobId.appendChild(txtJobId);
                    Element tagActionId = doc.createElement("ActionId");
                    tagJobDetail.appendChild(tagActionId);
                    Text txtActionId = doc.createTextNode(jobDetailI.getActionId().getActionId().toString());
                    tagActionId.appendChild(txtActionId);
                    Element tagActionName = doc.createElement("ActionName");
                    tagJobDetail.appendChild(tagActionName);
                    Text txtActionName = doc.createTextNode(jobDetailI.getActionId().getActionName());
                    tagActionName.appendChild(txtActionName);
                    Element tagItemId = doc.createElement("ItemId");
                    tagJobDetail.appendChild(tagItemId);
                    Text txtItemId = doc.createTextNode(jobDetailI.getItemId().getItemId().toString());
                    tagItemId.appendChild(txtItemId);
                    Element tagItemName = doc.createElement("ItemName");
                    tagJobDetail.appendChild(tagItemName);
                    Text txtItemName = doc.createTextNode(jobDetailI.getItemId().getItemName());
                    tagItemName.appendChild(txtItemName);
                    Element tagDescription = doc.createElement("Description");
                    tagJobDetail.appendChild(tagDescription);
                    Text txtDescription = doc.createTextNode(jobDetailI.getDescription().replace("\n", "<br/>"));
                    tagDescription.appendChild(txtDescription);
                }

                //TransformerFactory instance is used to create Transformer objects.
                TransformerFactory factory = TransformerFactory.newInstance();
                Transformer transformer = factory.newTransformer();

                transformer.setOutputProperty(OutputKeys.INDENT, "yes");

                // create string from xml tree
                StringWriter sw = new StringWriter();
                StreamResult result = new StreamResult(sw);
                DOMSource source = new DOMSource(doc);
                transformer.transform(source, result);
                String xmlString = sw.toString().replace("&#13;", "");

                out.println(xmlString);
                // Create xml

            } catch (Exception ex) {
            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
